<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
            @keyup.enter.native="handleFilter"
            clearable
            v-model="param.jobNumber"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入员工工号"
      ></el-input>

      <el-input
            @keyup.enter.native="handleFilter"
            clearable
            v-model="param.sectionNo"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工段编号"
      ></el-input>
      <el-date-picker
        :clearable="false"
        v-model="dateOptions"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="请选择开始时间"
        end-placeholder="结束时间"
        align="right"
        style="margin-right:15px;"
        />
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="员工姓名"  prop="userName" align="center" width="100px"/>
      <el-table-column  label="员工工号" prop='jobNumber' align="center" width="100px"/>
      <el-table-column  label="工时得分" prop='manHour' align="center"/>
      <el-table-column  label="质量得分" prop='quality' align="center"/>
      <el-table-column  label="领导评价得分" prop='leadership' align="center"/>
      <el-table-column  label="总分" prop='totalPoints' align="center"/>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>
  </div>
</template>

<script>
import { performanceStatisticsPage,getJobNumberScore } from '@/api/performance.js'
export default {
    data() {
        return {
            total: 0,                           //数据的总数
            listQuery: {
                endTime: '',                     //结束时间
                startTime: '',                   //开始时间
                page: 1,
                limit: 10
            },
            param: {
                jobNumber: '',                    //员工工号
                sectionNo: '',
            },
            tableInfo: [],
            loadingList: false,
            loading: false,
            pickerOptions: {
                shortcuts: [{
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    picker.$emit('pick', [start, end]);
                  }
                }, {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    picker.$emit('pick', [start, end]);
                  }
                }]
            },
            dateOptions: this.getNowTime()
        }
    },
    methods: {
      transformDat(res) {
      const mapInfo = {
        index: '序号',
        userName: '员工姓名',
        jobNumber: '员工工号',
        manHour: '工时得分',
        quality: '质量得分',
        leadership: '领导评价得分',
        totalPoints: '总分'
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      console.log('中文的表头', header)
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      console.log(data)
      return { header, data }
    },
          // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      if(this.dateOptions.length) {
        query.startTime = this.dateOptions[0]
        query.endTime = this.dateOptions[1]
      }
      if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
      if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
      query.page = 1
      query.limit = 10000
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)

      let arr = await getJobNumberScore(query)
      let dateString = this.dateOptions.length?this.dateOptions[0] + '-' + this.dateOptions[1]:''
      if(!arr.data.list.length) return this.$message.error('导出数据为空！')
      const { header, data } = this.transformDat(this.setSort(arr.data.list))
        import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: dateString + '绩效与质量excel', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
        // 排序函数
    setSort(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item,index)=>{
        let obj = {
          index: index+1,
          userName: item.userName,
          jobNumber: item.jobNumber,
          manHour: item.manHour,
          quality: item.quality,
          leadership: item.leadership,
          totalPoints: item.totalPoints
      }
      arr1.push(obj)
      })
      return arr1
    },
    // 搜索按钮绑定的函数，向服务器发送表单数据
    // 所有传输的表单字段都不是必须的，按需查询
    async handleFilter() {
      this.loadingList = true
      let query = Object.assign({},this.listQuery)
      if(this.dateOptions.length) {
        query.startTime = this.dateOptions[0]
        query.endTime = this.dateOptions[1]
      }
      if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
      if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
      // 用来判断查询的条件是否为空，当不为空时，则返回到首页，也就是第一页
      if(query.startTime == '' &&
         query.endTime == '' &&
         query.jobNumber == '' ) {
         console.log('搜索内容不为空')
      } else {
        query.page = 1
      }
      let {data} = await getJobNumberScore(query)
      this.tableInfo = data.list
      this.total = data.count
      this.loadingList = false
    },
    // 修改按钮绑定的函数，将整行的内容取好跳转到修改页面
    handleEdit(item) {
      this.$router.push({
        path: 'updateData_List',
        name: 'updateData_List',
        params: item
      })
    },
    // 删除用户按钮,使用elementui的messageBox弹框组件
    // 传入的数据是数据所在的行数以及该条目所有的信息
    handleDelete(index,row) {
      this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
          let res = await delPerformance({performanceId: row.performanceId})
          this.tableInfo.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //初始默认执行(重点)
    getNowTime() {
      let dateTime = +new Date()+8*3600*1000
      const start = new Date(dateTime - 3600 * 1000 * 24 * 30)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0] //默认开始时间7天前
      const end = new Date(dateTime)
        .toISOString()
        .replace('T', ' ')
        .split('.')[0]//默认结束时间当前时间
      console.log([start, end])
      return [start, end]
    },
     // 获取角色列表下拉框数据
    async getRoleInfo() {
      let {data} = await getRoleList()
      this.roleList = data
    },
    // 获取部门下拉框数据
    async getDepartInfo() {
      let {data} = await getDepartList()
      this.departList = data
    }, 
    // table表单下方的页码组件改变每页显示的数据条数
     handleSizeChange(val) {
      this.listQuery.limit = val
      this.handleFilter()
    },
    // table表单下方的页码组件改变页面
     handleCurrentChange(val) {
      this.listQuery.page = val
      this.handleFilter()
    }
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter()
  }

}
</script>

<style>

</style>